package com.example.postmsg;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import junit.framework.Assert;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ListActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.postmsg.HttpRequest;

public class MainActivity extends Activity {

	private String host = "XMG";
	private String remote = "XMG";
	private Thread get_thread,post_thread;
	private String str = "";
	private String URL = "http://lsc0825gae.appspot.com/gbb";
	private ListView listv;
	private EditText editText; 
	private List<Map<String, Object>> msg_list = new ArrayList<Map<String, Object>>();
	private Map<String, Object> map = new HashMap<String, Object>();
	private int remote_msg_ID=0,msg_ID=1;
	
	//timer
	Handler handler = new Handler() {
	    public void handleMessage(Message msg) {
	        update();
	        super.handleMessage(msg);
	    }
	};
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listv = (ListView) findViewById(R.id.listView1);
		editText=(EditText)findViewById(R.id.editText1);
		
		
	    
		}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public static String sendDataByPost(String url) { 
        HttpClient client = new DefaultHttpClient(); 
        HttpPost post = new HttpPost(url); 
        HttpResponse resp = null; 
        String result = ""; 
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(); 
        nameValuePair.add(new BasicNameValuePair("msg_ID", "zxg")); 
        try {
            post.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8)); 
            resp = client.execute(post); 
            result = EntityUtils.toString(resp.getEntity()); 
       } catch (IOException e) { 
    	    result = "catch";
            e.printStackTrace(); 
        }
        return result; 
    }
	
	
	
	public void onGETClick(View view)
	 {
			//String res = sendDataByPost("http://lsc0825gae.appspot.com/gbb");
			//Toast.makeText(this, "res:" + res, Toast.LENGTH_SHORT).show();
		//update();
        Toast.makeText(this, "Ip: " + str, Toast.LENGTH_LONG).show();
        new Thread(new MyThread()).start();
		
	 }
	
	public void onPOSTClick(View view)
	 {
			//String res = sendDataByPost("http://lsc0825gae.appspot.com/gbb");
			//Toast.makeText(this, "res:" + res, Toast.LENGTH_SHORT).show();

        Log.d("Main","Clicked");
        Log.d("VALUE",Integer.toString(1));
        //remote_msg_ID = Integer.valueOf(editText.getText().toString());
        String smsg = "failed chinese";
        try {
			smsg = new String(editText.getText().toString().getBytes("GBK"), HTTP.UTF_8);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	   while(Send_Msg(editText.getText().toString()) == false)
		   str = "";
	   msg_ID++;
	   Log.d("Main","After Send");
	   String userName = "";
	   String incoming = "";
	   try{
		   Log.d("Main","before JSON");
		   JSONObject json= new JSONObject(str);
		   Log.d("Main","1");
		   Log.d("STR",str);
	       JSONArray jsonArray=json.getJSONArray("msgs");
	       Log.d("Main","2");
	       for(int i =0;i<jsonArray.length();i++){
	       
	       
		       JSONObject jmsg=(JSONObject) jsonArray.get(i);
		       Log.d("Main","3");
		       userName=(String) jmsg.get("username");
		       remote_msg_ID = Integer.valueOf((String)jmsg.get("remote_msg_ID"));
		       incoming += (String) jmsg.get("msg");
		       if(i!=(jsonArray.length()-1))incoming += "\n";
	       }
	   }catch(Exception e){Log.d("Main","JSON catch");}
	   
	   if(!incoming.equals("")){
	   map = new HashMap<String, Object>();
       map.put("title", userName);
       //map.put("info", editText.getText().toString());
       map.put("info", incoming);
       msg_list.add(map);
	   }
       map = new HashMap<String, Object>();
       map.put("title", host);
       //map.put("info", editText.getText().toString());
       map.put("info", editText.getText().toString());
       editText.setText("");
       msg_list.add(map);
	   
       SimpleAdapter adapter = new SimpleAdapter(this,msg_list,R.layout.vlist,
               new String[]{"title","info"},
               new int[]{R.id.title,R.id.info});
       listv.setAdapter(adapter);
       listv.setSelection(listv.getAdapter().getCount()-1);
       str = "";
	 }
	
	public boolean Send_Msg(final String msg)
	{
		post_thread=new Thread(new Runnable() {  
	           
	           @Override  
	           public void run() {  
	               // TODO Auto-generated method stub  
	           	HttpRequest hr = new HttpRequest();
	           	List<NameValuePair> params = new ArrayList<NameValuePair>();  
	            params.add(new BasicNameValuePair("msg_ID", Integer.toString(msg_ID)));  
	            params.add(new BasicNameValuePair("remote_msg_ID", Integer.toString(remote_msg_ID)));
	            params.add(new BasicNameValuePair("username", host)); 
	            params.add(new BasicNameValuePair("msg", msg));  
	           		str = hr.doPost(URL, params);
				
						// TODO Auto-generated catch block
					//中文
	                      			  
	           }  
	       });  
	       post_thread.start();
	       while(post_thread.isAlive());
	       while(str.equalsIgnoreCase(""))
	       {
	    	   post_thread.start();
	       }
	       if(str.equalsIgnoreCase("no response"))
	       {
	    	   return false;
	       }
	    
		return true;
	}
	
	private boolean Get_Msg()
	{
		get_thread=new Thread(new Runnable() {  
            
            @Override  
            public void run() {  
                // TODO Auto-generated method stub  
            	HttpRequest hr = new HttpRequest();
	           	List<NameValuePair> params = new ArrayList<NameValuePair>();    
	            params.add(new BasicNameValuePair("remote_msg_ID", Integer.toString(remote_msg_ID)));
	            params.add(new BasicNameValuePair("username", host));  
            	try {

                    Log.d("Get","before doGet");
					str = hr.doGet(URL,params);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();

			        Log.d("Get","catch");
				}
                       			  
            }  
        });
        get_thread.start(); 
        Log.d("Get","after start");
        while(get_thread.isAlive());
	    while(str.equalsIgnoreCase(""))
	    {
	    	get_thread.start();

	        Log.d("Get","post thread");
	    }
	    if(str.equalsIgnoreCase("no response"))
	    {

	        Log.d("Get","false");
	    	return false;
	    }

        Log.d("Get","true");
			return true;
	}
	private void update()
	{
		 
		while(Get_Msg() == false);
		String userName = "";
	   String incoming = "";
	   try{
		   Log.d("Main","before JSON");
		   JSONObject json= new JSONObject(str);
		   Log.d("Main","1");
		   Log.d("STR",str);
	       JSONArray jsonArray=json.getJSONArray("msgs");
	       Log.d("Main","2");
	       for(int i =0;i<jsonArray.length();i++){
	       
	       
		       JSONObject jmsg=(JSONObject) jsonArray.get(i);
		       Log.d("Main","3");
		       userName=(String) jmsg.get("username");
		       remote_msg_ID = Integer.valueOf((String)jmsg.get("remote_msg_ID"));
		       incoming += (String) jmsg.get("msg");
		       if(i!=(jsonArray.length()-1))incoming += "\n";
	       }
	   }catch(Exception e){Log.d("Main","JSON catch");}
	   
	   if(!incoming.equals("")){
		map = new HashMap<String, Object>();
	    map.put("title", userName);
	    //map.put("info", editText.getText().toString());
	    map.put("info", incoming);
	    msg_list.add(map);
	   }
	   
    SimpleAdapter adapter = new SimpleAdapter(this,msg_list,R.layout.vlist,
            new String[]{"title","info"},
            new int[]{R.id.title,R.id.info});
    listv.setAdapter(adapter);
    listv.setSelection(listv.getAdapter().getCount()-1);
	}
	
	public class MyThread implements Runnable {
	    @Override
	    public void run() {
	        // TODO Auto-generated method stub
	        while (true) {
	            try {
	                Thread.sleep(5000);// 线程暂停10秒，单位毫秒
	                
	                Message message = new Message();
	                message.what = 1;
	                handler.sendMessage(message);// 发送消息
	            } catch (InterruptedException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }
	        }
	    }
	}
}


